package com.leetcode.sorts.tree;

import java.util.*;

/**
 * @Author: WuPeng
 * @Date: 2021/6/3 2:51 下午
 *
 * 637.二叉树的层平均值
 * 给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
 *
 */
public class LevelAverage_637 {
    public static List<Double> averageOfLevels(TreeNode root){
        List<Double> res = new ArrayList<>();
        if (root == null){
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            int level_size = queue.size();
            double sum = 0;
            for (int i = 0; i < level_size; i++) {
                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
            }
            res.add((sum / level_size));
        }
        return res;
    }

    public static void main(String[] args) {
        TreeNode left = new TreeNode(2147483647);
        TreeNode right = new TreeNode(2147483647);
        TreeNode root = new TreeNode(2147483647, left, right);

        List<Double> res = averageOfLevels(root);

        System.out.println(Arrays.toString(res.toArray()));
    }

}
